package com.xk.filter;

import com.alibaba.fastjson.JSON;
import com.xk.constants.DeskConstants;
import com.xk.domain.ResponseResult;
import com.xk.domain.entity.LoginUser;
import com.xk.enums.AppHttpCodeEnum;
import com.xk.utils.JwtUtil;
import com.xk.utils.RedisCache;
import com.xk.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 认证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    /**
     * redis工具类
     */
    @Autowired
    RedisCache redisCache;


    /**
     * 认证请求有没有携带token,进行认证
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        //判断token是否存在
        if (!StringUtils.hasText(token)){//返回可以是 不为NUll 的空字符串
            //放行 , 安全过滤器,会进行最后判断
            filterChain.doFilter(request,response);
            return;
        }
        //解析token,获取use ID
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token过期 和 token不对 , 过滤器当中不能直接抛出异常
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));//把错误信息响应给前端
            return;
        }
        //根据id查询Redis获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(DeskConstants.REDIS_STR_AND_USERID+claims.getSubject());
        //判断用户有没有登录超时
        if(Objects.isNull(loginUser)){
            //提现重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));//把错误信息响应给前端
            return;
        }
        //把用户信息存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);  //TODO 缺少用户权限信息传入, 后续补充
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
